package com.example.testlxr9096;

import android.util.Log;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.io.ModbusTCPTransaction;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersRequest;
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
import com.ghgande.j2mod.modbus.msg.WriteMultipleRegistersRequest;
import com.ghgande.j2mod.modbus.msg.WriteSingleRegisterRequest;
import com.ghgande.j2mod.modbus.msg.WriteSingleRegisterResponse;
import com.ghgande.j2mod.modbus.net.TCPMasterConnection;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleRegister;

import java.net.InetAddress;

public class ModbusTCPClient {

    private TCPMasterConnection connection;
    private final String ipAddress;
    private boolean isConnected = false;
    private final int port;

    public ModbusTCPClient(String ipAddress, int port) {
        this.ipAddress = ipAddress;
        this.port = port;
    }

    // 连接设备
    public boolean connect() {
        try {
            InetAddress address = InetAddress.getByName(ipAddress);
            connection = new TCPMasterConnection(address);
            connection.setPort(port);
            connection.setTimeout(3000); // 3秒超时
            connection.connect();
            isConnected = true;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 断开连接
    public void disconnect() {
        if (connection != null) {
            connection.close();
        }
        isConnected = false;
    }
    public synchronized boolean isConnected() {
        return isConnected;
    }

    // 读取保持寄存器（功能码03）
    public int[] readHoldingRegisters(int slaveId, int startAddress, int count) {



        try {
            ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
            ReadMultipleRegistersRequest request = new ReadMultipleRegistersRequest(startAddress, count);
            request.setUnitID(slaveId);
            transaction.setRequest(request);
            transaction.execute();

            ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse) transaction.getResponse();

            if (response != null) {

                Register[] registers = response.getRegisters();
                int[] values = new int[registers.length];
                for (int i = 0; i < registers.length; i++) {
                    values[i] = registers[i].getValue();
                    Log.d("cccl","recvc-"+i+"---"+values[2]);
                }

                return values;

            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }
//    public void testModbusConnection() {
//        int[] slaveIdsToTest = {1, 2, 255, 0}; // 测试这些从站ID
//        int[] addressesToTest = {0, 1, 2, 3, 4, 5}; // 测试这些地址
//        int[] functionCodesToTest = {3, 4}; // 测试功能码03和04
//
//        for (int slaveId : slaveIdsToTest) {
//            for (int address : addressesToTest) {
//                for (int functionCode : functionCodesToTest) {
//                    try {
//                        // 尝试连接和读取
//                        ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
//                        ReadMultipleRegistersRequest request;
//
//                        if (functionCode == 3) {
//                            request = new ReadMultipleRegistersRequest(address, 1);
//                        } else {
//                            request = new ReadMultipleRegistersRequest(address, 1);
//                        }
//
//                        request.setUnitID(slaveId);
//                        transaction.setRequest(request);
//                        transaction.setRetries(1); // 减少重试次数以加快测试
//                        transaction.execute();
//                        ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse) transaction.getResponse();
//
//                        if (response != null) {
//                            Log.d("TEST", "成功! SlaveID=" + slaveId +
//                                    ", Addr=" + address +
//                                    ", FC=" + functionCode);
//                            return;
//                        }
//                    } catch (Exception e) {
//                        // 忽略异常，继续测试
//                        Log.d("TEST", "失败: SlaveID=" + slaveId +
//                                ", Addr=" + address +
//                                ", FC=" + functionCode +
//                                ", Error: " + e.getMessage());
//                    }
//                }
//            }
//        }
//    }

    // 在ModbusTCPClient类中添加
    public boolean writeMultipleRegisters(int slaveId, int startAddress, int[] values) {
        try {
            ModbusTCPTransaction transaction = new ModbusTCPTransaction(connection);
            WriteMultipleRegistersRequest request = new WriteMultipleRegistersRequest(
                    startAddress,
                    convertToRegisters(values)
            );
            request.setUnitID(slaveId);
            transaction.setRequest(request);
            transaction.execute();
            return transaction.getResponse() != null;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    private Register[] convertToRegisters(int[] values) {
        Register[] registers = new Register[values.length];
        for (int i = 0; i < values.length; i++) {
            registers[i] = new SimpleRegister(values[i]);
        }
        return registers;
    }



}
